package com.rayson.yututu.aop;

import cn.hutool.core.util.StrUtil;
import com.rayson.yututu.annotation.AuthCheck;
import com.rayson.yututu.exception.BusinessException;
import com.rayson.yututu.exception.ErrorCodeEnum;
import com.rayson.yututu.model.entity.User;
import com.rayson.yututu.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Author: rayson
 * Description: 权限校验切面
 * Version: 1.0
 * Date: 2024-12-18 23:16
 */
@Aspect
@Component
public class AuthCheckAspect {

    @Resource
    private UserService userService;


    @Around("@annotation(authCheck)")
    public Object checkAuth(ProceedingJoinPoint joinPoint, AuthCheck authCheck) throws Throwable {
        String mustRole = authCheck.mustRole();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        User loginUser = userService.getLoginUser(request);
        if (StrUtil.isNotBlank(mustRole) && !mustRole.equals(loginUser.getUserRole())) {
            throw new BusinessException(ErrorCodeEnum.NO_AUTH, "无权限访问");
        }
        return joinPoint.proceed();
    }
}
